package com.ykq.filter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: tui-education
 * @description:
 * @author: 闫克起2
 * @create: 2022-04-14 08:58
 **/
@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        //判断当前得请求是否为sso/login请求 放行
        //获取请求路径
        String path = request.getPath().toString();
        String method = request.getMethod().toString();
        if("post".equalsIgnoreCase(method)&&StringUtils.hasText(path)&&path.contains("/sso/login")){
             return chain.filter(exchange);
        }
        //获取请求头token 判断token是否为null //jwt校验token  如果不为null且校验
        //获取请求头
        String token = request.getHeaders().getFirst("token");
        if(StringUtils.hasText(token)){
            try {
                JWTVerifier build = JWT.require(Algorithm.HMAC256("ykq-AAA")).build();
                DecodedJWT verify = build.verify(token);
                //判断redis中是否存在该token
                Boolean aBoolean = redisTemplate.hasKey(token);
                if(aBoolean){
                     return chain.filter(exchange);//放行
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        //不放行得内容
        //如果未登录，自定义响应内容
        DataBuffer buffer=null;
        try {
//          CommonResult commonResult=new CommonResult(401,"请先登录",null);
            Map<String,Object> commonResult=new HashMap<>();
            commonResult.put("code",401);
            commonResult.put("msg","请先登录");
            ObjectMapper objectMapper=new ObjectMapper();
            byte[] datas=objectMapper.writeValueAsString(commonResult).getBytes("utf-8");
            buffer = response.bufferFactory().wrap(datas);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response.writeWith(Mono.just(buffer));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
